package com.example.pm.controller.noallowaop;


import cn.hutool.core.date.LocalDateTimeUtil;
import com.example.pm.common.basic.perm.PermInter;
import com.example.pm.common.constant.SystemConstant;
import com.example.pm.common.redis.RedisUtils;
import com.example.pm.common.result.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * 上传操作
 **/
@RestController
@Api(value = "上传管理", tags = {"上传管理"})
@RequestMapping(value = "/upload", method = {RequestMethod.POST, RequestMethod.GET})
public class UploadController {
    @Autowired
    private RedisUtils redisUtils;

    /* 图片 */
    @ResponseBody
    @ApiOperation("上传图片")
    @RequestMapping(value = "/image", method = RequestMethod.POST)
    @PermInter(perm = ":upload:image", name = "上传图片")
    private R<String> uploadImageUtil(MultipartFile file) {
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取日期，拼接到文件名中，避免文件名重复
        String[] dayTime = LocalDateTimeUtil.formatNormal(LocalDateTime.now()).replace(":", "-").split(" ");
        String day = dayTime[0];
        String time = dayTime[1];
        String path = SystemConstant.IMAGE_Upload + day + "\\" + time;//想要存储文件的地址

        // 检测是否存在该目录
        if (!new File(path).exists()) {
            new File(path).mkdirs();
        }
        fileName = path + "\\" + fileName;
        try {
            try (FileOutputStream fos = new FileOutputStream(fileName)) {
                // 写入文件
                fos.write(file.getBytes());
            }
            String key = day + "-" + time;
            redisUtils.set(key, fileName, 10);
            return R.ok(null, key);
        } catch (IOException e) {
            System.out.println("Exception:" + e);
        }
        return R.fail("上传失败");
    }
}
